<?php
namespace app\admin\controller;

use OSS\OssClient;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use think\Controller;

class File extends Admin
{
    public function uploadImg()
    {
        if(empty($_FILES['file'])){
            json_error_msg("请选择文件！");
        }
        if($_FILES['file']['error'] != 0) {
            if ($_FILES['file']['error'] == 1 || $_FILES['file']['error'] == 2) {
                json_error_msg("超过了系统设定的文件大小");
            } elseif ($_FILES['file']['error'] == 3) {
                json_error_msg(' 文件只有部分被上传');
            } elseif ($_FILES['file']['error'] == 4) {
                json_error_msg(' 没有文件被上传');
            } elseif ($_FILES['file']['error'] == 5) {
                json_error_msg(' 上传文件大小为0');
            } else {
                json_error_msg('文件上传失败');
            }
        }
        $dicname = input('dicName','projectfile','trim');
        //名字获取
        $file_name= date('YmdHis').rand(1,999).$_FILES['file']['name'];//拼装存储地址path
       $filekey = $this->uploadSysFileToOSS($_FILES['file']['tmp_name'],$file_name,$dicname);
       $res["file"] = "https://file.hot68.cn/htqpfile/".$dicname."/".$filekey;
//        $res["file"] = "https://file.hot68.cn/htqpfile/paypic/20241229210334287logo.png";
        $res["file_name"] = $file_name;
        json_success_msg($res);
    }

    /**
     * 上传项目文件
     */
    public function uploadFile()
    {
        if(empty($_FILES['file'])){
            json_error_msg("请选择文件！");
        }
        if($_FILES['file']['error'] != 0) {
            if ($_FILES['file']['error'] == 1 || $_FILES['file']['error'] == 2) {
                json_error_msg("超过了系统设定的文件大小");
            } elseif ($_FILES['file']['error'] == 3) {
                json_error_msg(' 文件只有部分被上传');
            } elseif ($_FILES['file']['error'] == 4) {
                json_error_msg(' 没有文件被上传');
            } elseif ($_FILES['file']['error'] == 5) {
                json_error_msg(' 上传文件大小为0');
            } else {
                json_error_msg('文件上传失败');
            }
        }
        //名字获取
        $filesExt = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);//获取文件后缀
        if (!in_array($filesExt, ['xls','xlsx', 'XLS','XLSX', 'csv'])) {
            json_error_msg('文件类型错误');
        }
        $dicname = input('dicName','projectfile','trim');

        $file_name= date('YmdHis').rand(1,999).$_FILES['file']['name'];//拼装存储地址path
       $filekey = $this->uploadSysFileToOSS($_FILES['file']['tmp_name'],$file_name,$dicname);
       $res["file"] = "https://file.hot68.cn/htqpfile/".$dicname."/".$filekey;
//         $res["file"] = "https://file.hot68.cn/htqpfile/projectfile/202503261154531308888.xlsx";
        $res["file_name"] = $file_name;
        $size = $_FILES['file']['size'];
        if($size < 1024){
            $size = $size.'b';
        }elseif (round($size/1024,2) < 1024){
            $size = round($size/1024,2).'Kb';
        }else{
            $size = round($size/1024/1024,2).'Mb';
        }
        $res["file_size_info"] = $size;
        $res["file_size"] = $_FILES['file']['size'];
        $filePath = $_FILES['file']['tmp_name'];
        $objPHPExcel = IOFactory::load($filePath);
        $res['data'] = $this->ndataHandle($objPHPExcel);
        json_success_msg($res);
    }

    private function uploadSysFileToOSS($filepath,$filename,$dicname){
        vendor('OSS.src.OSS.OssClient');
        vendor('OSS.Common');
        vendor('OSS.Config');
        $config = array(
            'KeyId' => 'LTAI4GH2fKDxQGVheJZXKnd7',
            'KeySecret' => 'aP2lIjWuspC5D6E1ATgXezESgsuHF0',
            'Endpoint' => 'oss-cn-beijing.aliyuncs.com',
            'Bucket' => 'gangboshi',
        );
        $ossClient = new OssClient($config['KeyId'], $config['KeySecret'],$config['Endpoint'], false);
        if (is_null($ossClient)) json_error_msg('上传失败');
        //*******************************简单使用***************************************************************
        //上传本地文件
        try{
            $result = $ossClient->uploadFile($config['Bucket'],'htqpfile/'.$dicname.'/'.$filename,$filepath);
        }catch (\Exception $e){
            json_error_msg($e->getMessage());
        }
        return $filename;
    }

    /**
     * 2022-12-24
     * @param $objPHPExcel
     * @return array
     */
    public function ndataHandle($objPHPExcel){
        $info = [];
        $sheet = $objPHPExcel->getActiveSheet();
        $highestRow = $sheet->getHighestRow();

        $name_A1 = $objPHPExcel->getActiveSheet()->getCell("A1")->getValue();
        $name_B1 = $objPHPExcel->getActiveSheet()->getCell("B1")->getValue();
        $name_C1 = $objPHPExcel->getActiveSheet()->getCell("C1")->getValue();
        /*if(trim($name_A1) != '零件名称' || trim($name_B1) != 'OE码' || (trim($name_C1) && trim($name_C1) != '数量')){
            json_error_msg('数据格式有误，请确认');
        }*/
        $eq_name_arr = [];
        for($i = 2; $i <= $highestRow; $i++){
            $eq_name = trim($objPHPExcel->getActiveSheet()->getCell("A".$i)->getFormattedValue());
            if($eq_name == '运费和木架') continue;
            $oe_no = trim($objPHPExcel->getActiveSheet()->getCell("B".$i)->getFormattedValue());
            $num = trim($objPHPExcel->getActiveSheet()->getCell("C".$i)->getFormattedValue());
            $eq_name_arr[] = $eq_name;
            $data = [
                'eq_name'=>$eq_name,
                'oe_no'=>$oe_no,
                'num'=>$num?:1,
                'qulity_service_state'=>0,
                'qulity_org_state'=>0,
                'qulity_matching_state'=>0,
                'qulity_complete_state'=>0,
                'qulity_suitable_state'=>0,
                'common'=>'',
            ];
            $info[] = $data;
        }
        /*$uniqueArray = array_unique($eq_name_arr);
        if(count($eq_name_arr) != count($uniqueArray)){
            json_error_msg('有重复零件，请确认');
        }*/
        return $info;
    }


    public function download(){
        $filePath = input('filePath');
        $fileSize = input('fileSize');
        $readBuffer = 1024;
        //设置头信息
        //声明浏览器输出的是字节流
        header('Content-Type: application/octet-stream');
        //声明浏览器返回大小是按字节进行计算
        header('Accept-Ranges:bytes');
        //告诉浏览器文件的总大小
//        $fileSize = filesize($filePath);//坑 filesize 如果超过2G 低版本php会返回负数
        header('Content-Length:' . $fileSize); //注意是'Content-Length:' 非Accept-Length
        //声明下载文件的名称
        header('Content-Disposition:attachment;filename=' . basename($filePath));//声明作为附件处理和下载后文件的名称
        //获取文件内容
        $handle = fopen($filePath, 'rb');//二进制文件用‘rb’模式读取
        while (!feof($handle) ) { //循环到文件末尾 规定每次读取（向浏览器输出为$readBuffer设置的字节数）
            echo fread($handle, $readBuffer);
        }
        fclose($handle);//关闭文件句柄
        exit;
    }
}

